package mygw.jtthink.com.filters;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

@Component
public class MyHeaderGatewayFilterFactory
        extends AbstractGatewayFilterFactory<MyHeaderGatewayFilterFactory.Config> {
    public MyHeaderGatewayFilterFactory(){
        super(Config.class);
    }

    public List<String> shortcutFieldOrder(){
        return Arrays.asList("hName","hValue");
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            //myname shenyi
            ServerHttpRequest newRequest= exchange.getRequest().mutate()
                    .header(config.gethName(),new String[]{config.gethValue()}).build();
            return chain.filter(exchange.mutate().request(newRequest).build())
                    .then(Mono.fromRunnable(()->{
                        exchange.getResponse().getHeaders()
                                .put("version",Arrays.asList("1.1"));
            }));
        };
    }
    public static class Config{
        private String hName;//自定义头的 key
        private String hValue;//自定义头的 值

        public String gethName() {
            return hName;
        }

        public void sethName(String hName) {
            this.hName = hName;
        }

        public String gethValue() {
            return hValue;
        }

        public void sethValue(String hValue) {
            this.hValue = hValue;
        }
    }

}
